﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using UniCT.LinkShareWpf.Interface;
using System.Xml.Serialization;

namespace UniCT.LinkShareWpf.Runtime
{

    [Serializable]
    [XmlRoot("MyNode")]
    public class MyNode
    {
        #region Static
        private static MyNode _instance = null;

        public static MyNode Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new MyNode();
                return _instance;
            }
        }
        #endregion

        private HashSet<Node> _nodes;

        [XmlAttribute("Id")]
        public Guid Id
        {
            get;
            set;
        }



        [XmlArray("MyNodes")]
        [XmlArrayItem("Node")]
        public HashSet<Node> Nodes
        {
            get { return _nodes; }
        }


        public MyNode()
        {
            _nodes = new HashSet<Node>();
            Id = Guid.NewGuid();
           
        }

        public Boolean Contains(Node node)
        {
            bool check = false;
            foreach (Node nod in this._nodes)
            {

                if (nod.Uri.Equals(node.Uri))
                {
                    check = true;
                    break;
                }
            }
            return check;
        }


        public void Save()
        {
            XmlSerializer xs = null;
            try
            {
                xs = new XmlSerializer(typeof(MyNode));
            }
            catch { Console.WriteLine("SAVE 1"); }

            using (StreamWriter sw = new StreamWriter("MyNode.xml", false))
            {

                try
                {
                    xs.Serialize(sw, this);
                }
                catch { Console.WriteLine("SAVE 2"); }
            }
        }

        public static MyNode Read()
        {
            MyNode ret = null;
            XmlSerializer xs = null;
            try
            {

                xs = new XmlSerializer(typeof(MyNode));
            }
            catch
            {
                Console.WriteLine("read 1");
            }
            try
            {
                using (StreamReader sr = new StreamReader("MyNode.xml"))
                {
                    ret = xs.Deserialize(sr) as MyNode;
                }
            }
            // Se il file non esiste vuol dire che è la prima esecuzione
            // e si crea un nuovo kad
            catch
            {
                ret = new MyNode();
                Console.WriteLine("read 2");
            }

            return ret;
        }


    }
}
